package xt.outfood.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xt.outfood.common.CustomException;
import xt.outfood.entity.Category;
import xt.outfood.entity.Dish;
import xt.outfood.entity.Setmeal;
import xt.outfood.mapper.CategoryMapper;
import xt.outfood.service.CategoryService;
import xt.outfood.service.DishService;
import xt.outfood.service.SetmealService;

/**
 * @author 小小爱欧
 * @date 2022/7/21 15:23
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id来删除分类，删除之前需判断是否有关联
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //删除前查询分类是否关联菜品，如果关联，则抛出一个异常，如select count(*) from dish where category_id=?
        //添加条件，eq为等值查询
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        long count = dishService.count(dishLambdaQueryWrapper);
        if (count > 0) {
            //已经关联菜品，抛出一个异常,抛出的异常需要进行捕获处理
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }
        //删除前查询是否关联套餐，如果已经关联，则抛出一个异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据id进行查询
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        long count1 = setmealService.count(setmealLambdaQueryWrapper);
        if (count1 > 0) {
            //已经关联，抛出一个异常
            throw new CustomException("当前分类下关联了套餐，不能删除");

        }
        //若两个都没关联，则正常删除分类
        super.removeById(id);

    }
}
